<?php

declare(strict_types=1);

namespace App\Repository;
/**
 * 标签数据访问层
 * 作者 薛原
 * 日期 2025-10-17
 */
use App\Model\Tag;
use Hyperf\Di\Annotation\Inject;

class TagRepository
{
    #[Inject]
    private Tag $tagModel;

    /**
     * 返回字典类型数据集
     * @param $ids
     * @param string $key
     * @return array
     */
    public function getDicByIds($ids, $key = "tag_id")
    {
        $tag_list = $this->tagModel->whereIn("id",$ids)->select(["id","name"])->get()->toArray();
        return \App\Lib\DataFormart::dataToDic($tag_list);
    }

    /**
     * 检测和创建标签
     * 用于创建文章时
     * @param $tags
     */
    public function checkAndCreateTags($tags)
    {
        $tags = array_unique($tags);
        $check_result = $this->tagModel->whereIn("name",$tags)->select(["id","name"])->get()->toArray();
        $ret = [];
        $cache_arr = [];
        foreach($check_result as $info){
            $cache_arr[] = $info['name'];

        }
        $need_insert_data = array_diff($tags, $cache_arr);
        //$datas = [];
        foreach($need_insert_data as $info){
            $obj = [];
            $obj['name'] = $info;
            $obj['slug'] = strtolower($info);
            //$datas[] = $obj;
            //好像没有insertAll方法
            $this->tagModel->insert($obj);
        }
    }

    /**
     * 根据name获取list数据
     * @param $names
     * @return array
     */
    public function getDataByNames($names): array
    {
        return $this->tagModel->whereIn("name",$names)->select("id","name")->get()->toArray();
    }
    /**
     * 标签引用次数+1
     * 创建文章时调用
     * @param $tags
     */
    public function incTagsCount($tags)
    {
        $this->tagModel->whereIn("name",$tags)->increment("article_count");
    }
    /**
     * 标签引用次数-1
     * 删除文章时调用
     * @param $tags_ids
     */
    public function decTagsCountByIds($tags_ids)
    {
        $ret = $this->tagModel->whereIn("id",$tags_ids)->where("article_count",0)->count();
        if($ret > 0){
            return false;
        }
        $this->tagModel->whereIn("id",$tags_ids)->decrement("article_count");
        return true;
    }
}